package net.plankton.mjpeg;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.HashMap;
import java.util.Map;

public class DataStructure {

	public static final String RIFF_SIZE = "riffSize";
	public static final String HDRL_SIZE = "hdrlSize";
	public static final String BUFFER_SIZE = "bufferSize";
	public static final String STRL_SIZE = "strlSize";
	public static final String STRF_SIZE = "strfSize";
	public static final String IMGDATA_SIZE = "imgDataSize";
	public static final String MOVI_START = "moviStart";
	public static final String MOVI_LENGTH = "moviLENGTH";
	public static final String IDX_SIZE = "idxSize";
	
	private static final String TMP = "sdfsdahguahsdguioaweioghsivksvökl";
	
	public DataStructure(RandomAccessFile file)
	{
		this.file=file;
	}
	
	private RandomAccessFile file;

	private Map<String,Long> pointers = new HashMap<String,Long>();

	/**
	 * @return the file
	 */
	public RandomAccessFile getFile() {
		return file;
	}

	/**
	 * @param file the file to set
	 */
	public void setFile(RandomAccessFile file) {
		this.file = file;
	}

	/**
	 * @return the riffSize
	 */
	public void restorePointer(String name) throws IOException{
		Long pointer = getPointer(name);
		file.seek(pointer);
	}

	Long getPointer(String name) throws IOException {
		Long pointer = pointers.get(name);
		if (pointer==null)
			throw new IOException("pointer "+name+" not found");
		return pointer;
	}

	/**
	 * @param riffSize the riffSize to set
	 */
	public void storePointer(String name) throws IOException{
		pointers.put(name,file.getFilePointer());
		writeInt(0);
	}
	
	public void writeLength(String name,long endPosition) throws IOException {
		long startPointer = getPointer(name);
		long size = endPosition-(startPointer+4);
		bookmark();
		restorePointer(name);
		writeInt((int)size);
		back();
	}

	public void back() throws IOException {
		restorePointer(TMP);
	}

	public void bookmark() throws IOException {
		storePointer(TMP);
	}
	
	public void writeLength(String name) throws IOException {
		writeLength(name,file.getFilePointer());
	}
	
	public void writeLength(String name,String endName) throws IOException {
		writeLength(name,getPointer(endName));
	}
	
	final void writeString(String s) throws IOException {
        byte[] bytes =  s.getBytes("UTF-8");
        file.write(bytes);
    }

    final void writeInt(int v) throws IOException {
        file.write(v & 0xFF);
        file.write((v >>>  8) & 0xFF);
        file.write((v >>> 16) & 0xFF);
        file.write((v >>> 24) & 0xFF);
    }

    final void writeShort(int v) throws IOException {
        file.write(v& 0xFF);
        file.write((v >>> 8) & 0xFF);
    }

	
	
	
}
